package com.luwanglin.remoting.transport.socket;

import com.luwanglin.config.CustomShutdownHook;
import com.luwanglin.config.RpcServiceConfig;
import com.luwanglin.factory.SingletonFactory;
import com.luwanglin.provider.ServiceProvider;
import com.luwanglin.provider.impl.ZkServiceProviderImpl;
import com.luwanglin.utils.concurrent.threadpool.ThreadPoolFactoryUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.*;
import java.util.concurrent.ExecutorService;

import static com.luwanglin.remoting.transport.netty.server.NettyRpcServer.PORT;

@Slf4j
@Component
public class SocketRpcServer {
    private final ExecutorService threadPol;
    private final ServiceProvider serviceProvider;

    public SocketRpcServer() {
        threadPol = ThreadPoolFactoryUtils.createCustomThreadPoolIfAbsent("socket-server-rpc-pool");
        serviceProvider = SingletonFactory.getInstance(ZkServiceProviderImpl.class);
    }

    public void registerService(RpcServiceConfig rpcServiceConfig) {
        serviceProvider.publishService(rpcServiceConfig);
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket()) {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            serverSocket.bind(new InetSocketAddress(hostAddress, PORT));
            CustomShutdownHook.getCustomShutdownHook().clearAll();
            Socket socket;
            while ((socket = serverSocket.accept()) != null) {
                log.info("client connected [{}]", socket.getInetAddress());
                threadPol.execute(new SocketRpcRequestHandlerRunnable(socket));
            }
            threadPol.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
